package com.goldplusgold.tradedelay.app.my.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.AppCollectedInfoUtil;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.DeviceNetworkUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.my.networkservice.ApiConfig;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.pojo.CodeInfo;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.AppInfoUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.RegexUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


public class RegisterFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.txt_phoneNum)
    TextView txtPhoneNum;
    @BindView(R.id.et_phoneNum)
    EditText etPhoneNum;
    @BindView(R.id.txt_vericode)
    TextView txtVericode;
    @BindView(R.id.et_vericode)
    EditText etVericode;
    @BindView(R.id.btn_get_register_vericode)
    TextView btnGetRegisterVericode;
    @BindView(R.id.txt_login_pwd)
    TextView txtLoginPwd;
    @BindView(R.id.et_register_pwd)
    EditText etRegisterPwd;
    @BindView(R.id.cb_protocal)
    CheckBox cbProtocal;
    @BindView(R.id.txt_protocol)
    TextView txtProtocol;
    @BindView(R.id.iv_delete_phone)
    ImageView ivDeletePhone;
    private int curTime;
    private String mUserName;
    private String mPassword;
    private String mCode;
    private Timer timer;
    private Handler handler = new Handler(this);

    public static RegisterFragment newInstance() {
        RegisterFragment fragment = new RegisterFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_register;
    }

    @Override
    protected void initView() {
        super.initView();

        cbProtocal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbProtocal.setChecked(true);
                } else {
                    cbProtocal.setChecked(false);
                }
            }
        });
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    etPhoneNum.setVisibility(View.VISIBLE);
                } else {
                    etPhoneNum.setVisibility(View.GONE);
                }
            }
        });
    }

    private void setTimerTask() {
        curTime = 60;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Message msg = new Message();
                msg.what = 3;
                handler.sendMessage(msg);
                curTime--;
            }
        }, 0, 1000);
    }

    private void codeCountDown() {
        if (curTime == 0) {
            timer.cancel();
            btnGetRegisterVericode.setText(R.string.get_vericode_again);
            btnGetRegisterVericode.setTextColor(getActivity().getResources().getColor(R.color.title_bg));
            btnGetRegisterVericode.setEnabled(true);
        } else {
            btnGetRegisterVericode.setText("(" + curTime + "s)" + getString(R.string.repeat_after_sixty_seconds));
            btnGetRegisterVericode.setTextColor(getActivity().getResources().getColor(R.color.title_bg));
        }
    }


    @OnClick({R.id.iv_back, R.id.iv_delete_phone, R.id.btn_get_register_vericode, R.id.cb_protocal, R.id.txt_protocol, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                getActivity().onBackPressed();
                break;
            case R.id.iv_delete_phone:
                etPhoneNum.setText("");
                break;
            case R.id.btn_get_register_vericode:
                mUserName = etPhoneNum.getText().toString().trim();
                if (TextUtils.isEmpty(mUserName)) {
                    showToastMessage(getString(R.string.please_enter_phone_number), Toast.LENGTH_SHORT);
                    return;
                }
                if (!RegexUtils.checkMobile(mUserName)) {
                    showToastMessage(getString(R.string.wrong_phone_number), Toast.LENGTH_SHORT);
                } else {
                    new GetRegisterCodeAsyncTask().execute(AsyncTask.TYPE_NET);
                }
                break;
            case R.id.txt_protocol:
                ActivityUtils.gotoActionBrowserPage(getActivity(), ApiConfig.SERVICE_PROTOCOL);
                break;
            case R.id.btn_register:
                mCode = etVericode.getText().toString().trim();
                mPassword = etRegisterPwd.getText().toString().trim();
                if (!cbProtocal.isChecked()) {
                    showToastMessage(getString(R.string.agree_xieyi_can_register), Toast.LENGTH_SHORT);
                    return;
                }
                if (TextUtils.isEmpty(mCode)) {
                    showToastMessage(getString(R.string.please_enter_vericode), Toast.LENGTH_SHORT);
                    return;
                }
                if (TextUtils.isEmpty(mPassword)) {
                    showToastMessage(getString(R.string.please_enter_pwd), Toast.LENGTH_SHORT);
                    return;
                }

                if (!RegexUtils.checkPassword(mPassword)) {
                    showToastMessage(getString(R.string.password_format_promat), Toast.LENGTH_SHORT);
                    return;
                }
                String imei = DeviceNetworkUtil.getIMEI(getContext());
                new RegisterAsyncTask(imei).execute(AsyncTask.TYPE_NET);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (isAvailableActivity()) {
            int type = msg.what;
            switch (type) {
                case 3:
                    codeCountDown();
                    break;
                case NetWorkConstant.NETWORK_ERROR_CODE:
                    showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                    break;
                case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                    String errorMessage = (String) msg.obj;
                    showToastMessage(errorMessage, Toast.LENGTH_LONG);
                    break;
            }
        }
        return true;
    }

    public class GetRegisterCodeAsyncTask extends AsyncTask<Void, Void, CodeInfo> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected CodeInfo doInBackground(Void... params) {
            try {
                CodeInfo codeInfo = MyService.getInstance().getRegisterCode(mUserName);
                if (codeInfo != null) {
                    return codeInfo;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(CodeInfo codeInfo) {
            super.onPostExecute(codeInfo);
            if (codeInfo == null) {
                return;
            }
            if (codeInfo.getStatus()) {
                setTimerTask();
                btnGetRegisterVericode.setEnabled(false);
            }
        }
    }

    public class RegisterAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        private String imei;

        public RegisterAsyncTask(String imei) {
            this.imei = imei;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            try {
                UserInfo userInfo = MyService.getInstance().userRegister("android", mUserName, mPassword, "android", mCode, imei);
                if (userInfo != null) {
                    return userInfo;
                }

            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo != null) {
                String token = userInfo.getToken();
                String time = String.valueOf(System.currentTimeMillis());
                String versionName = AppInfoUtils.getVersionName(getActivity());
                AppCollectedInfoUtil.initAppCollectedInfo(getActivity(), token, time, versionName);
                getActivity().setResult(Activity.RESULT_OK);
                finishActivity();
            }
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
